package services

import (
	"github.com/didi/nightingale/src/models"
)

var (
	Services              = make(map[string]*models.ServiceCollect)
	ServicesWithScheduler = make(map[string]*ServiceScheduler)
)

func DelNoUseServiceCollect(newCollect map[string]*models.ServiceCollect) {
	for currKey, currService := range Services {
		newService, ok := newCollect[currKey]
		if !ok || currService.LastUpdated != newService.LastUpdated {
			deleteService(currKey)
		}
	}
}

func AddNewServiceCollect(newCollect map[string]*models.ServiceCollect) {
	for target, newService := range newCollect {
		if _, ok := Services[target]; ok && newService.LastUpdated == Services[target].LastUpdated {
			continue
		}

		Services[target] = newService
		sch := NewServiceScheduler(newService)
		ServicesWithScheduler[target] = sch
		sch.Schedule()
	}
}

func deleteService(key string) {
	v, ok := ServicesWithScheduler[key]
	if ok {
		v.Stop()
		delete(ServicesWithScheduler, key)
	}
	delete(Services, key)
}
